package com.ruoyi.fun.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.fun.domain.EcCategory;
import com.ruoyi.fun.service.IEcCategoryService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 移动端商品分类Controller（无需权限验证）
 * 
 * @author ruoyi
 * @date 2025-01-15
 */
@Anonymous
@RestController
@RequestMapping("/mobile/category")
public class EcMobileCategoryController extends BaseController
{
    @Autowired
    private IEcCategoryService ecCategoryService;

    /**
     * 查询所有商品分类列表（移动端公开接口）
     */
    @GetMapping("/list")
    public TableDataInfo list(EcCategory ecCategory)
    {
        // 只返回正常状态的分类
        ecCategory.setStatus("0");
        ecCategory.setOrgId(getOrgId());
        
        startPage();
        List<EcCategory> list = ecCategoryService.selectEcCategoryList(ecCategory);
        return getDataTable(list);
    }
    
    /**
     * 查询树形商品分类列表（移动端公开接口）
     * @param orgId 组织ID，如果不传则默认使用103
     */
    @GetMapping("/tree")
    public TableDataInfo tree(Long orgId)
    {
        try {
            // 如果前端没有传递orgId，则使用默认值
            if (orgId == null) {
                orgId = getOrgId(); // 从BaseController获取默认组织ID
            }
            
            System.out.println("[移动端分类树] 使用组织ID: " + orgId);
            
            EcCategory ecCategory = new EcCategory();
            // 只返回正常状态的分类
            ecCategory.setStatus("0");
            ecCategory.setOrgId(orgId);
            
            List<EcCategory> list = ecCategoryService.selectEcCategoryList(ecCategory);
            
            // 确保list不为null
            if (list == null) {
                list = new java.util.ArrayList<>();
            }
            
            System.out.println("[移动端分类树] 查询到分类数量: " + list.size());
            
            // 构建树形结构
            List<CategoryTreeNode> treeList = buildCategoryTree(list);
            
            TableDataInfo dataInfo = new TableDataInfo();
            dataInfo.setCode(200);
            dataInfo.setMsg("查询成功");
            dataInfo.setRows(treeList);
            dataInfo.setTotal(treeList.size());
            
            return dataInfo;
        } catch (Exception e) {
            System.out.println("获取分类树异常: " + e.getMessage());
            e.printStackTrace();
            
            TableDataInfo dataInfo = new TableDataInfo();
            dataInfo.setCode(500);
            dataInfo.setMsg("获取分类树失败: " + e.getMessage());
            dataInfo.setRows(new java.util.ArrayList<>());
            dataInfo.setTotal(0);
            
            return dataInfo;
        }
    }
    
    /**
     * 测试查询所有组织的分类数据
     */
    @GetMapping("/testAllOrgs")
    public TableDataInfo testAllOrgs()
    {
        try {
            System.out.println("=== 测试查询所有组织的分类数据 ===");
            
            EcCategory ecCategory = new EcCategory();
            ecCategory.setStatus("0");
            // 不设置orgId，查询所有组织的数据
            
            List<EcCategory> list = ecCategoryService.selectEcCategoryList(ecCategory);
            
            // 确保list不为null
            if (list == null) {
                list = new java.util.ArrayList<>();
            }
            
            System.out.println("查询到的分类总数: " + list.size());
            
            // 统计各个组织ID的数据量
            java.util.Map<Long, Integer> orgCountMap = new java.util.HashMap<>();
            for (EcCategory category : list) {
                Long orgId = category.getOrgId();
                orgCountMap.put(orgId, orgCountMap.getOrDefault(orgId, 0) + 1);
            }
            
            System.out.println("各组织ID的分类数量:");
            for (java.util.Map.Entry<Long, Integer> entry : orgCountMap.entrySet()) {
                System.out.println("组织ID " + entry.getKey() + ": " + entry.getValue() + " 个分类");
            }
            
            TableDataInfo dataInfo = new TableDataInfo();
            dataInfo.setCode(200);
            dataInfo.setMsg("查询成功，共" + list.size() + "个分类");
            dataInfo.setRows(list);
            dataInfo.setTotal(list.size());
            
            return dataInfo;
            
        } catch (Exception e) {
            System.out.println("测试查询异常: " + e.getMessage());
            e.printStackTrace();
            
            TableDataInfo dataInfo = new TableDataInfo();
            dataInfo.setCode(500);
            dataInfo.setMsg("查询失败: " + e.getMessage());
            dataInfo.setRows(new java.util.ArrayList<>());
            dataInfo.setTotal(0);
            
            return dataInfo;
        }
    }
    
    /**
     * 构建分类树形结构
     */
    private List<CategoryTreeNode> buildCategoryTree(List<EcCategory> categories) {
        List<CategoryTreeNode> treeList = new java.util.ArrayList<>();
        
        // 找出所有父级分类（parentId为0或null）
        for (EcCategory category : categories) {
            if (category.getParentId() == null || category.getParentId() == 0) {
                CategoryTreeNode treeNode = new CategoryTreeNode();
                treeNode.setCategoryId(category.getCategoryId());
                treeNode.setParentId(category.getParentId());
                treeNode.setCategoryName(category.getCategoryName());
                treeNode.setCategoryCode(category.getCategoryCode());
                treeNode.setCategoryIcon(category.getCategoryIcon());
                treeNode.setCategoryImage(category.getCategoryImage());
                treeNode.setSortOrder(category.getSortOrder());
                treeNode.setStatus(category.getStatus());
                
                // 查找子分类
                List<CategoryTreeNode> children = findChildren(category.getCategoryId(), categories);
                treeNode.setChildren(children);
                
                treeList.add(treeNode);
            }
        }
        
        return treeList;
    }
    
    /**
     * 递归查找子分类
     */
    private List<CategoryTreeNode> findChildren(Long parentId, List<EcCategory> categories) {
        List<CategoryTreeNode> children = new java.util.ArrayList<>();
        
        for (EcCategory category : categories) {
            if (category.getParentId() != null && category.getParentId().equals(parentId)) {
                CategoryTreeNode childNode = new CategoryTreeNode();
                childNode.setCategoryId(category.getCategoryId());
                childNode.setParentId(category.getParentId());
                childNode.setCategoryName(category.getCategoryName());
                childNode.setCategoryCode(category.getCategoryCode());
                childNode.setCategoryIcon(category.getCategoryIcon());
                childNode.setCategoryImage(category.getCategoryImage());
                childNode.setSortOrder(category.getSortOrder());
                childNode.setStatus(category.getStatus());
                
                // 递归查找子分类的子分类
                List<CategoryTreeNode> grandChildren = findChildren(category.getCategoryId(), categories);
                childNode.setChildren(grandChildren);
                
                children.add(childNode);
            }
        }
        
        return children;
    }
    
    /**
     * 分类树节点类
     */
    public static class CategoryTreeNode {
        private Long categoryId;
        private Long parentId;
        private String categoryName;
        private String categoryCode;
        private String categoryIcon;
        private String categoryImage;
        private Integer sortOrder;
        private String status;
        private List<CategoryTreeNode> children;
        
        // Getters and Setters
        public Long getCategoryId() { return categoryId; }
        public void setCategoryId(Long categoryId) { this.categoryId = categoryId; }
        
        public Long getParentId() { return parentId; }
        public void setParentId(Long parentId) { this.parentId = parentId; }
        
        public String getCategoryName() { return categoryName; }
        public void setCategoryName(String categoryName) { this.categoryName = categoryName; }
        
        public String getCategoryCode() { return categoryCode; }
        public void setCategoryCode(String categoryCode) { this.categoryCode = categoryCode; }
        
        public String getCategoryIcon() { return categoryIcon; }
        public void setCategoryIcon(String categoryIcon) { this.categoryIcon = categoryIcon; }
        
        public String getCategoryImage() { return categoryImage; }
        public void setCategoryImage(String categoryImage) { this.categoryImage = categoryImage; }
        
        public Integer getSortOrder() { return sortOrder; }
        public void setSortOrder(Integer sortOrder) { this.sortOrder = sortOrder; }
        
        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }
        
        public List<CategoryTreeNode> getChildren() { return children; }
        public void setChildren(List<CategoryTreeNode> children) { this.children = children; }
    }
    /**
     * 根据id和组织ID获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:ecmobilecategory:query')")
    @GetMapping(value = "/{id}/org/{orgId}")
    public AjaxResult getInfoByOrgId(@PathVariable("id") Long id, @PathVariable("orgId") Long orgId)
    {
        return success(ecCategoryService.selectEcCategoryByCategoryIdAndOrgId(id, orgId));
    }

    /**
     * 根据组织ID查询列表
     */
    @PreAuthorize("@ss.hasPermi('system:ecmobilecategory:list')")
    @GetMapping("/org/{orgId}")
    public TableDataInfo listByOrgId(@PathVariable Long orgId)
    {
        startPage();
        EcCategory ecCategory = new EcCategory();
        List<EcCategory> list = ecCategoryService.selectEcCategoryListByOrgId(ecCategory, orgId);
        return getDataTable(list);
    }


}